Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

String basics

String declaration & Initialization

String declaration

In Java, a String is declared as a variable with the type String. Here’s how you can declare a String:
String declaration String str;
In this case, str is a reference that can point to a String object. However, it’s not yet initialized and doesn’t point to anything.

String Initialization

To initialize a String, you can use a String literal, which is a sequence of characters within double quotes:
String initialization String str = "Hello, World!";
In this case, str is a String reference that points to a String object that contains the text ""Hello, World!"". There are two main ways to declare and initialize String objects in Java

By using literal

Java has a special feature called String literal. In this case, a String object is created in the String constant pool.
By literal String s1 = "Hello"; // String literal

By using new keyword

In this case, a String object is created in the heap memory.
Using new keyword String s2 = new String("Hello"); // Using 'new' keyword
The difference between these two methods lies in the memory area where the String object is created. When we create a String using a String literal, the JVM checks the String constant pool first. If the String already exists, it returns the reference of the pooled String instance. If the String doesn’t exist, it creates a new String in the String constant pool and its reference will be returned. When we use the new keyword, JVM creates the String object in heap memory and the reference is returned. It doesn’t check whether the object is already available in the String constant pool or not. Here’s an example to illustrate the difference:
String literal vs new keyword String s1 = ""Hello""; // String literal String s2 = ""Hello""; // String literal String s3 = new String(""Hello""); // Using 'new' keyword System.out.println(s1 == s2); // true, because both refer to the same object in the String constant pool System.out.println(s1 == s3); // false, because s3 refers to an instance in the heap, a different object
In the above example, s1 and s2 are pointing to the same object in the String constant pool, while s3 points to another object in the heap, even though the text in the String is the same. This is why s1 == s2 is true, but s1 == s3 is false. The == operator checks whether two references point to the same object, not their values. To compare the values of two String objects, you should use the equals() method. For example, s1.equals(s3) would return true in this case. Remember, String is one of the most important classes in Java. It’s used in almost every application. Understanding how to declare, initialize, and use it is a critical skill for any Java programmer.

  📌TAGS

★String ★java ★string methods ★ concatenation ★ declaration ★ initialization

Tutorials